﻿using MongoDB.Driver;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.ESG.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sustainalytics.ScreeningTool.Synchronization.Caches
{
    public class ControversyTemplatesCache : DictionaryCache<Guid, HashSet<string>>
    {
        public HashSet<string> this[Guid companyId] => GetValueOrEmpty(companyId, new HashSet<string>());
    }

    public class ControversyTemplatesCacheLoader : ICacheLoader<ControversyTemplatesCache>
    {
        private readonly ControversyTemplatesCache cache;
        private readonly IMongoCollection<RPControversyIndicator> collection;

        public ControversyTemplatesCacheLoader(
            ControversyTemplatesCache cache,
            IMongoCollection<RPControversyIndicator> collection)
        {
            this.cache = cache;
            this.collection = collection;
        }

        public async Task LoadAsync(ClientFacingProduct clientFacingProduct)
        {
            var values = await collection
                .Find(_ => true)
                .Project(x => new { x.CompanyId, x.Template.Number })
                .ToListAsync();

            var items = values
                .GroupBy(x => x.CompanyId)
                .ToDictionary(grp => grp.Key, grp => grp.Select(x => x.Number).ToHashSet());

            cache.AddItems(items);
        }
    }
}
